package com.atguigu.gmall.cart.interceptor;

import com.atguigu.gmall.cart.config.JwtProperties;
import com.atguigu.gmall.common.bean.UserInfo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class CartInterceptor implements HandlerInterceptor {

    @Autowired
    JwtProperties properties;

    public static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userkey = CookieUtils.getCookieValue(request, properties.getUserKey());
        if (StringUtils.isEmpty(userkey)){
            userkey = UUID.randomUUID().toString();
            CookieUtils.setCookie(request,response,"user-key",userkey,properties.getExpire());
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserKey(userkey);
        //获取用户登录信息 token
        String token = CookieUtils.getCookieValue(request, properties.getCookieName());
        if (StringUtils.isNotBlank(token)){
            //解析token
            Map<String, Object> infoFromToken = JwtUtils.getInfoFromToken(token, properties.getPublicKey());
            userInfo.setUserId(Long.valueOf(infoFromToken.get("userId").toString()));
        }
        THREAD_LOCAL.set(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }

    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }
}
